<?php 

require 'vendor/autoload.php';

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$host = '127.0.0.1';
$port = 6379;
$connection = new \Redis();
$connection->connect($host, $port);

$queue_key = 'mail_task';

while (true) {
	$timeout = 2;
	$message = $connection->brpop($queue_key, $timeout);
	if (empty($message)) {
		continue;
	}
	$message = json_decode($message[1], true);

	$begin = microtime(true);	
	send_mail($message);
	$end = microtime(true);
	$elapse = (int)(($end - $begin) * 1000);

	if ($elapse > 100) {
		continue;
	} else {
		$sleep_time = (100 - $elapse) * 1000;
		//echo 'sleep ', $sleep_time, 'us', PHP_EOL;
		usleep($sleep_time);
	}
}

function send_mail($message) {

try {

		$transport = (new Swift_SmtpTransport('127.0.0.1', 25));

	$mailer = new Swift_Mailer($transport);


$messaged = (new Swift_Message($message["subject"]))
  ->setFrom(['root@panview.cn' => '潘潘邮箱验证码'])
  ->setTo([$message["receiver"]])
  ->setBody($message["body"]);

$mailer->send($messaged);
		usleep(10 * 1000);
		//echo '邮件发送完毕.', PHP_EOL;
		throw new \Exception('连接不上邮件服务器。');
		
	} catch (\Exception $ex) {
		my_error_log('邮件发送失败', ['message' => json_encode($message), 'exception' => $ex->getMessage()]);	
	}
}

function my_error_log($log_text, $context) {
	$log = new Logger('send_mail');
	$log->pushHandler(new StreamHandler(__DIR__ . '/app.log', Logger::WARNING));

	// add records to the log
	$log->error($log_text, $context);
}

